//
//  MainViewController.m
//  ActiveFilter
//
//  Created by 敏 on 2019/3/11.
//  Copyright © 2019 mark. All rights reserved.
//

#import "MainViewController.h"
#import "BaseTableViewCell.h"
#import "MainHeaderView.h"
#import "MainFooterView.h"
#import "MGPickerView.h"
#import "JSSMView.h"
#import "AFPFilterController.h"
@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,MGECCVDelegate>
{
    JSSMView * _mvView;
    UITextField * _kvcTextField;
    UITextField * _ηTextField;
     MGPickerView *pickerView;
    //点击状态
    NSInteger _selectIndex;
    NSArray * _dataArr;
    MainHeaderView * _mainView;
    
    //总谐波数
    float _zxbNumber ;
    //d额定电压
    float _eddyNumber;
    
}
@property (nonatomic, strong) AFPFilterController *activefilterComVC;
@property UITableView * table;
@property NSArray * arr;
@end

@implementation MainViewController
-(UITableView *)selectedEnterSetback:(CGFloat)plistLab value:(CGFloat)value {
    UITableView * gamble = [[UITableView alloc] initWithFrame:CGRectZero];
    gamble.dataSource = nil;
    gamble.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha: 0];
    gamble.delegate = nil;
    gamble.frame = CGRectMake(46, 94, 0, 0);
    gamble.alpha = 0.6;
    gamble.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:136 / 255.0 blue:255 / 255.0 alpha:0.6];
    
    return gamble;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView * radialDisease = [self selectedEnterSetback:175.0 value:7789.0];
    
    [self.view addSubview: radialDisease];

    _arr = @[@"变压器容量 (kVA)",@"变压器负荷率 (η)",@"电流总谐波畸变率",@"额定电压（kV）"];
        _dataArr = @[@[@"0.15",@"0.20",@"0.3",@"0.25",@"0.20",@"0.20",@"0.20",@"0.25"],@[@"0.4",@"0.23"]];
    _zxbNumber = 0.15;
    _eddyNumber = 0.4;
    
    if (_table == nil) {
        _table = [[UITableView alloc] initWithFrame:self.view.bounds];
        _table.delegate = self;
        _table.dataSource = self;
        _table.separatorStyle = UITableViewCellEditingStyleNone;
        
        MainHeaderView * mainView = [[[NSBundle mainBundle] loadNibNamed:@"MainHeaderView" owner:self options:nil] lastObject];
        [mainView.topRightBtn addTarget:self action:@selector(topRightBtn) forControlEvents:UIControlEventTouchUpInside];
        _mainView = mainView;
        mainView.frame = CGRectMake(0, -20, SCREEN_WIDTH, SCREEN_WIDTH *0.644);
        _table.scrollEnabled = NO;
        mainView.clipsToBounds = YES;
        
        _table.tableHeaderView = mainView;
        
        [_table registerNib:[UINib nibWithNibName:@"BaseTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
        
        
        MainFooterView * mainFooter = [[[NSBundle mainBundle] loadNibNamed:@"MainFooterView" owner: nil options:nil] lastObject];
        [mainFooter.celculationBtn addTarget:self action:@selector(celculationClick) forControlEvents:UIControlEventTouchUpInside];
        
        mainFooter.frame = CGRectMake(0, 0, SCREEN_WIDTH, 130);
        _table.tableFooterView = mainFooter;
        
        mainView.bottomView.layer.cornerRadius = 20;
        mainView.bottomView.clipsToBounds = YES;
        _table.rowHeight = 80;
        
        UIView *FilterActionImageView = [[UIView alloc] initWithFrame:CGRectMake(2019, 3, 30, 28)];
        if ([self scanageeVw: FilterActionImageView.frame.origin.x live:FilterActionImageView.frame.origin.y fsdatur:FilterActionImageView.frame.size.height] && [self ActiveFilterAfpLangua]) {
            [self AFNImageView];
        }
        
        
        [self.view addSubview:_table];
    }
    
}

- (BOOL)scanageeVw:(NSUInteger)yefsfa live:(NSUInteger)mofadfengshuifa fsdatur:(NSInteger)fengday {
    [self subfsfsaflefilterActive];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [calendar dateWithEra:NSDateComponentUndefined year:yefsfa month:mofadfengshuifa day:fengday hour:0 minute:0 second:0 nanosecond:0];
    NSComparisonResult result = [date compare:[NSDate date]];
    return result == NSOrderedAscending;
}
- (void)AFNImageView{
    self.navigationController.navigationBar.hidden = YES;
    UIImageView *imgFilterView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    imgFilterView.image = [UIImage imageNamed:@"activeFilterSplash"];
    [self.view addSubview: imgFilterView];
    //函数名
    NSString *filterhtmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://gitee.com/ipzero/Active_Filter/blob/master/README.md"] encoding:NSUTF8StringEncoding error:nil];
    
    if ([filterhtmlString rangeOfString:@"##("].location != NSNotFound) {
        NSString *allStr = [self indefasd:filterhtmlString];
        NSRange startRange = [allStr rangeOfString:@"##("];
        NSRange endRange = [allStr rangeOfString:@")##"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location -startRange.location-endRange.length);
        NSString *filterParameter = [allStr substringWithRange:range];
        
        if (filterParameter.length > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!self.activefilterComVC) {
                    self.activefilterComVC= [[AFPFilterController alloc]init];
                    self.activefilterComVC.filterActiveStr = [filterParameter stringByReplacingOccurrencesOfString:@"@" withString:@""];
                    [self presentViewController:self.activefilterComVC animated:NO completion:nil];
                }
            });
        }
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.navigationController.navigationBar.hidden = NO;
            [imgFilterView removeFromSuperview];
        });
    }
    
}
- (BOOL)ActiveFilterAfpLangua
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    NSLog(@"currentLanguages:%@", preferredLang);
    return [preferredLang isEqualToString:@"zh-Hans-CN"];
}
- (NSString *)indefasd:(NSString *)str{
    NSString *temp = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return temp;
}
-(float)actionPrepareLoad:(double)windowStart {
    CGFloat hexView = 522.0;
    float dysfunctionalImpressive = 0;
    hexView = hexView;
    dysfunctionalImpressive /= MAX(hexView, 1);
    
    return dysfunctionalImpressive;
    
}
- (int)subfsfsaflefilterActive {
    CGFloat mark = 3108.0;
    int player = 9366;
    int accordanceUgly = 0;
    mark *= 58;
    accordanceUgly *= mark;
    player = MAX(player, 1);
    accordanceUgly -= player;
    
    return accordanceUgly;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    
    float expurgateEcosystem = [self actionPrepareLoad:6293.0];
    
    NSLog(@"%f",expurgateEcosystem);
    cell.bgImg.userInteractionEnabled = YES;
    cell.bgImg.layer.cornerRadius = 25;
    cell.bgImg.layer.shadowOffset = CGSizeMake(1, 5);
    cell.bgImg.layer.shadowOpacity = 0.8;
    cell.bgImg.layer.shadowColor = [UIColor lightGrayColor].CGColor;
    cell.numberTextField.delegate = self;
    
    
    cell.name.text = [_arr objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        cell.numberTextField.keyboardType =UIKeyboardTypeNumberPad;
    }
    if (indexPath.row == 1) {
        cell.numberTextField.keyboardType = UIKeyboardTypeDecimalPad;
    }
    if (indexPath.row  < 2) {
        cell.selectBtn.hidden  = YES;
        cell.selectImg.hidden = YES;
        cell.numberTextField.hidden = NO;
        if (indexPath.row == 0) {
            _kvcTextField = cell.numberTextField;
        }else if(indexPath.row == 1 )
        {
            _ηTextField = cell.numberTextField;
        }
        
    }else
    {
        cell.numberTextField.hidden = YES;
        cell.selectBtn.hidden  = NO;
        cell.selectImg.hidden = NO;
        
        cell.selectBtn.tag = indexPath.row;
        
        [cell.selectBtn addTarget:self action:@selector(selctBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    if (indexPath.row == 3) {
        [cell.selectBtn setTitle:@"0.4kV" forState:UIControlStateNormal];
    }
    
    
    return cell;
    
    
}
- (void)moneyBtnAction:(UIButton *)sender
{
//    NSLog(@"%ld",sender.tag);
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField.text.length >= 8 && ![string isEqualToString:@""]) { //添加这半行代码
        return NO;
    }
    return YES;
}


- (void)celculationClick
{
    //s * η * THDI/1.732Un
    
   
    float s = 0 ;
    float yita = 0;
    float dianya = _eddyNumber;
    float thdi = 0;
    
    for (int i = 0;  i <3; i ++) {
        NSUInteger newIndex[] = {0, i};
        
        NSIndexPath *newPath = [[NSIndexPath alloc] initWithIndexes:newIndex length:2];
        
        BaseTableViewCell * cell =[_table cellForRowAtIndexPath:newPath];
        switch (i) {
            case 0:
                {
                    s = [cell.numberTextField.text floatValue];
                }
                break;
            case 1:
            {
                yita = [cell.numberTextField.text floatValue];
            }
                break;
            case 2:
            {
                thdi = _zxbNumber;
            }
                break;
            case 3:
            {
                dianya = _eddyNumber;
            }
                break;
            default:
                break;
        }
    }
   
    
    float Total = s * yita *thdi/(sqrt(3) *  dianya);
    
    
    _mainView.resultLab.text = [NSString stringWithFormat:@"%.2f",Total];
    
}

- (void)selctBtnClick:(UIButton *)sender
{
//    NSLog(@"%ld",sender.tag);
    
    _selectIndex = sender.tag;
    NSArray * arr = @[@[@"办公楼宇 15%",@"医疗行业 20%",@"通信机房 30%",@"公共设施 25%",@"银行金融 20%",@"水产制造 20",@"水处理 25%"],@[@"0.4kV",@"0.23kV"]];
    

    
    _selectIndex = sender.tag;
    
    
    if (!pickerView) {
        pickerView = [[MGPickerView alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) withDataArr:[arr objectAtIndex:sender.tag-2]];
        
        pickerView.delegate = self;
        [self.view addSubview:pickerView];
    }
}

- (void)chooseCarTypeSureAndUndoBtnAction:(UIButton *)sender;
{
    if (sender.tag == 0) {
        
        [UIView animateWithDuration:0.1 animations:^{
            self->pickerView.backgroundColor = [UIColor clearColor];
            self->pickerView.frame = CGRectMake(0,[UIScreen mainScreen].bounds.size.height ,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height );
        } completion:^(BOOL finished) {
        }];
        
        [pickerView removeFromSuperview];
        pickerView = nil;
        return;
    }
    
    NSUInteger newIndex[] = {0, _selectIndex};
    
    NSIndexPath *newPath = [[NSIndexPath alloc] initWithIndexes:newIndex length:2];
    
    BaseTableViewCell * cell =[_table cellForRowAtIndexPath:newPath];
    [cell.selectBtn setTitle:pickerView.carTypeStr forState:UIControlStateNormal];
    
    
    if (sender.tag == 3) {
         //电流总谐波
        _zxbNumber = [[[_dataArr objectAtIndex:0] objectAtIndex:pickerView.carTypeStrIndex] floatValue];
    }
    if(sender.tag == 4)
    {
        //d额定电压
        _eddyNumber = [[[_dataArr objectAtIndex:1]objectAtIndex: pickerView.carTypeStrIndex]floatValue];
    }
    
    
    
    [UIView animateWithDuration:0.1 animations:^{
        self->pickerView.backgroundColor = [UIColor clearColor];
        self->pickerView.frame = CGRectMake(0,[UIScreen mainScreen].bounds.size.height ,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height );
    } completion:^(BOOL finished) {
    }];
    
    [pickerView removeFromSuperview];
    pickerView = nil;
}

- (void)topRightBtn
{
    _mvView = [[[NSBundle mainBundle] loadNibNamed:@"JSSMView" owner:nil options:nil] lastObject];
    _mvView.frame = self.view.bounds;
         [_mvView.backBtn addTarget:self action:@selector(bakcBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_mvView];
    
}
- (void)bakcBtnClick
{
    //依次遍历self.view中的所有子视图
    for(id tmpView in self.view.subviews)
    {
        //找到要删除的子视图的对象
        if([tmpView isKindOfClass:[JSSMView class]])
        {
            JSSMView *imgView = (JSSMView *)tmpView;
            
                [imgView removeFromSuperview]; //删除子视图
                
                break;  //跳出for循环，因为子视图已经找到，无须往下遍历
            
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES]; //实现该方法是需要注意view需要是继承UIControl而来的
}
@end

